package net.csiit.tools.fileserver.common.dto;

import lombok.Getter;
import lombok.Setter;

import java.util.Collection;

/**
 * @author adam
 * @date 2021-02-24
 */
@Getter
@Setter
public class R<T> {

    /**
     * 成功
     */
    public static final String CODE_SUCCESS = "0";
    /**
     * 请求失败
     */
    public static final String CODE_PARAM_ERROR = "400";

    private T content;
    /**
     * 错误消息  排错用
     */
    private String message;

    private long totalElements;

    /**
     * 返回码， 0成功，其他失败
     */
    private String code;

    public R() {
        this.code = CODE_SUCCESS;
    }

    public R(T content, long totalElements) {
        this();
        this.content = content;
        this.totalElements = totalElements;
    }

    public static <T> R<T> ok(T data, int totalElements) {
        return new R<>(data, totalElements);
    }

    public static <T> R<T> ok(T data, long totalElements) {
        return new R<>(data, totalElements);
    }

    public static <T> R<T> ok(T data) {
        if (data instanceof Collection) {
            return new R<>(data, ((Collection) data).size());
        } else {
            return new R<>(data, 0);
        }
    }

    public static <T> R<T> fail(String code, String message) {
        R<T> r = new R<>();
        r.setMessage(message);
        r.setCode(code);
        return r;
    }

    public static <T> R<T> fail(String message) {
        R<T> r = new R<>();
        r.setMessage(message);
        r.setCode(CODE_PARAM_ERROR);
        return r;
    }
}
